import fetch from 'isomorphic-fetch'
import validate from '../tools/validate'

export const POST_REGFROM = 'POST_REGFROM'
export const RESET_STATE = 'RESET_STATE'

export function resetState(reg) {
  return {
     type: RESET_STATE,
     reg : reg
  }
}

export function handleChange(key,e) {
  return (dispatch, getState) => {
    let value = e.target.value,data = {};
    data[key] = value;
    dispatch(resetState(eachValidate(data)))
    console.log(getState())
  }
}

export function postFetachAfter(dispatch,data) {
  if (data.code == 200) {
    //login successful 
    console.log('login successful');
    window.location.href = '#/center';
  } else {
    dispatch(resetState(data));
  }
}

function postRegAPI(data) {
  return {
    API : {
      data: data,
      url: 'http://www.peas_pencil.com/api.php',
      callback: function(dispatch,jsonData){
          postFetachAfter(dispatch,jsonData);
      }
    }
  }
}

export function postRegForm() {
  return (dispatch, getState) => {
    const { login } = getState();
    console.log(43,login,getState());
    if (boolValidate(login)) {
        dispatch(postRegAPI(login));
    }
  }
}

function boolValidate(obj) {
  let bool = true;
  for (var i in obj) {
      if (obj[i] !== '' && i.indexOf('Error') > -1) {
          bool = false;
      }
  }
  return bool;
}

function eachValidate(formData,dispatch) {
   let bool = true,objData={};
   let obj = validate(formData);
   for (var i in obj) {
        objData[i] = obj[i].value;
        if (!obj[i].bool) {
            objData[i+'Error'] = obj[i].text;
            bool = false;
        } else {
            objData[i+'Error'] = '';
        }
   }
   console.log(objData);
   return objData;
}
